# -*- coding: utf-8 -*-
import smtplib
import sys
import io
import requests
from lxml import etree
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
from datetime import datetime

# 设置标准输出编码为UTF-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')

my_sender = '2878225944@qq.com'  # 填写发信人的邮箱账号
my_pass = 'yjymiryhjyqvdgea'  # 发件人邮箱授权码
my_user = '1755592115@qq.com'  # 收件人邮箱账号
jie = '3484525706@qq.com'



def get_daily_sentence():
    """获取每日英语句子"""
    try:
        url = 'https://dict.eudic.net/home/dailysentence/'
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        r = requests.get(url, headers=headers, timeout=10)
        r.encoding = 'utf-8'
        text = r.text
        html = etree.HTML(text)

        # 提取英文和中文句子
        en = html.xpath('/html/body/div/div[2]/div[1]/div[2]/p[1]/text()')
        zh = html.xpath('/html/body/div/div[2]/div[1]/div[2]/p[2]/text()')

        if en and zh:
            english_sentence = en[0].strip()
            chinese_sentence = zh[0].strip()
            return english_sentence, chinese_sentence
        else:
            return "No sentence found today.", "今日未找到句子。"

    except Exception as e:
        print(f"获取每日句子失败: {e}")
        return "Failed to get sentence.", "获取句子失败。"


def send_mail():
    ret = True
    try:
        # 获取每日句子
        english, chinese = get_daily_sentence()
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # 创建邮件对象
        msg = MIMEMultipart('related')
        msg['From'] = formataddr(["每日英语", my_sender])
        msg['To'] = formataddr(["收件人", my_user,])
        msg['Subject'] = f"每日英语学习 {datetime.now().strftime('%Y-%m-%d')}"

        # 创建HTML内容
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <style>
                body {{
                    font-family: 'Microsoft YaHei', Arial, sans-serif;
                    margin: 0;
                    padding: 0;
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    min-height: 100vh;
                }}
                .container {{
                    max-width: 600px;
                    margin: 0 auto;
                    background: white;
                    border-radius: 20px;
                    overflow: hidden;
                    box-shadow: 0 20px 40px rgba(0,0,0,0.1);
                    margin-top: 20px;
                    margin-bottom: 20px;
                }}
                .header {{
                    background: linear-gradient(135deg, #ff6b6b 0%, #feca57 100%);
                    color: white;
                    padding: 40px 30px;
                    text-align: center;
                }}
                .content {{
                    padding: 40px 30px;
                }}
                .sentence-en {{
                    font-size: 24px;
                    font-weight: bold;
                    color: #2c3e50;
                    line-height: 1.6;
                    text-align: center;
                    margin-bottom: 20px;
                    font-style: italic;
                }}
                .sentence-zh {{
                    font-size: 18px;
                    color: #7f8c8d;
                    line-height: 1.6;
                    text-align: center;
                    margin-bottom: 30px;
                }}
                .image-section {{
                    text-align: center;
                    margin: 30px 0;
                    padding: 20px;
                    background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
                    border-radius: 15px;
                }}
                .footer {{
                    text-align: center;
                    padding: 20px;
                    background: #34495e;
                    color: #bdc3c7;
                    font-size: 12px;
                }}
                .date {{
                    background: rgba(255,255,255,0.2);
                    display: inline-block;
                    padding: 8px 20px;
                    border-radius: 20px;
                    margin-top: 10px;
                    font-size: 14px;
                }}
                .emoji {{
                    font-size: 48px;
                    margin-bottom: 20px;
                }}
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <div class="emoji">📚</div>
                    <h1 style="margin:0; font-size: 32px;">每日英语学习</h1>
                    <div class="date">{current_time}</div>
                </div>

                <div class="content">
                    <div class="sentence-en">
                        "{english}"
                    </div>
                    <div class="sentence-zh">
                        {chinese}
                    </div>

                    <div class="image-section">
                        <h3 style="color: #333; margin-bottom: 20px;">🎉 坚持学习，每天进步！</h3>
                        <img src="https://staticv2.hi2future.com/upload/emotion/tsj/t_0034.gif" 
                             alt="Learning GIF" 
                             style="max-width: 200px; border-radius: 15px; border: 4px solid white; box-shadow: 0 8px 25px rgba(0,0,0,0.15);">
                        <p style="margin-top: 15px; color: #666; font-size: 14px;">每天一句英语，积累无限可能</p>
                    </div>
                </div>

                <div class="footer">
                    <p>📧 邮件为每日16点内时间段自动发出，来自</p>
                    <p>🔔 如需拒收可联系发件人，或者拉入黑名单</p>
                    <p style="margin-top: 10px; opacity: 0.7;">&copy; {datetime.now().strftime('%Y')} 每日多邻国英语学习计划</p>
                </div>
            </div>
        </body>
        </html>
        """

        # 纯文本版本（备用）
        text_content = f"""
每日英语 - {datetime.now().strftime('%Y-%m-%d')}

英文句子:
{english}

中文翻译:
{chinese}

{'-' * 50}
邮件为每日15点自动发出，来自
如需拒收可联系发件人，或者拉入黑名单
        """

        # 添加HTML内容
        msg.attach(MIMEText(html_content, 'html', 'utf-8'))
        # 添加纯文本内容（某些邮箱客户端可能不支持HTML时显示）
        msg.attach(MIMEText(text_content, 'plain', 'utf-8'))

        # 发送邮件
        server = smtplib.SMTP_SSL("smtp.qq.com", 465)
        server.login(my_sender, my_pass)
        server.sendmail(my_sender, [my_user,jie ], msg.as_string())
        server.quit()

        print(f"每日英语邮件发送成功 - {current_time}")
        print(f"英文: {english}")
        print(f"中文: {chinese}")
        return True

    except Exception as e:
        error_msg = f"邮件发送失败 - 错误信息: {str(e)}"
        print(error_msg)
        return False


if __name__ == "__main__":
    try:
        success = send_mail()
        sys.exit(0 if success else 1)
    except Exception as e:
        print(f"脚本执行异常: {str(e)}")
        sys.exit(1)


